<script setup>
import { reactive, ref, onMounted,} from 'vue';
import { ElMessage } from 'element-plus';
import MapSelector from '../common/MapSelector.vue';
import { orderTypeMap, statusMap } from '@/utils/dict';
import { useRouter } from 'vue-router';
import { queryPageList, updateWorkorder,deleteOrder ,getOrderDetail} from '@/apis/workorderAPI';
const router=useRouter();
const archivedWorkorder = ref([]);
const isEditDialogOpen = ref(false);
const currentWorkorder = reactive({
  id:'',
  title:'',
  des:'',
  name:'',
  phone:'',
  address:'',
  status:'',
  pic:''
});
const addressInfo = ref({
  address: '',
  longitude: '',
  latitude: ''
});
const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);         // 每页条数，

//  编辑功能
const openDialog = (workorder) => {
  // 复制当前设备数据到编辑表单
  Object.keys(currentWorkorder).forEach(k => delete currentWorkorder[k])
  Object.assign(currentWorkorder, workorder);
  isEditDialogOpen.value = true;
};
const loading = ref(true);
//  保存编辑
const saveWorkorder =async () => {
  try{
    console.log("完整的编辑数据",currentWorkorder);
    const response=await updateWorkorder(currentWorkorder);
    console.log("后端返回的信息",response);
    ElMessage.success("编辑成功");
    fetchData();
  }catch{
    ElMessage.error("编辑失败");
  }finally{
    isEditDialogOpen.value=false;
  }

};
  const params = reactive({
      pageNo:'', // 从1开始
      pageSize: '',
      startDate:'',
      status:5
    });
// 6. 删除功能
const deleteWorkorder = async(workorder) => {
  const deleteId = workorder.id;
  try {
    await deleteOrder(deleteId);
    // 后端删除成功后，删除本地列表中的对应数据
    const index = archivedWorkorder.value.findIndex(item => item.id === deleteId);
    fetchData();
    if (index !== -1) {
     archivedWorkorder.value.splice(index, 1);
    }
    ElMessage.success('删除成功');
    fetchData();
  } catch {
    ElMessage.error("删除失败");
  }
};

const toDetail=(row)=>{
   router.push({
    path: `/orderDetail/${row.id}`, // 动态路由路径
  });
};
 const total=ref(0);
onMounted(async () => {
  await fetchData();
});
const fetchData = async () => {
  try {
    loading.value = true;
    params.pageNo = currentPage.value;
    params.pageSize = pageSize.value;
    const { data } = await queryPageList(params);
    const { records } = data;

    archivedWorkorder.value = records;
    total.value = data.total;
    console.log('返回的数据:', data);
    console.log('records:', records);
    console.log('workorderList:', archivedWorkorder.value);

  } catch (error) {
    console.error('错误:', error);
    ElMessage.error("加载失败");
  } finally {
    loading.value = false;
  }
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData(); // 重新请求
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData(); // 重新请求
};
const handleSearch=()=>{
  params.pageNo=1;
   console.log("搜索参数:", params);
  fetchData();
};
const  currentId=ref();
// 打开弹窗的方法
const dialogVisible=ref(false);
const isOpenDialog = (id) => {
  currentId.value=id;
  fetchDetail();
  dialogVisible.value=true;

};
const detailData=ref({});
const feedback=ref({});
const fetchDetail=async()=>{
  try{
    const response = await getOrderDetail(currentId.value);
    const { data } = response;
    detailData.value = data;
    feedback.value = data.feedback || {};
  }catch{
    ElMessage.error("加载失败");
  }
};
</script>
<template>
  <div class="container">
    <div class="workorder-header">
     <div class="search-box">
        <!-- <el-select v-model="params.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select> -->
        <el-date-picker  v-model="params.startDate" type="date"  placeholder=" 创建时间"  style="margin-left: 10px; width: 150px;"  value-format="YYYY-MM-DD HH:mm:ss"/>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
     </div>
    </div>
     <h1>归档工单</h1>
    <div class="table_container">
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 数据为空 -->
    <div v-else-if="archivedWorkorder.length === 0" class="empty">
      暂无数据
    </div>
    <div v-else>
    <el-table  :data="archivedWorkorder"  border  style="width: 900px; margin-top: 45px; " >
      <el-table-column label="id" prop="id"  min-width="80%" width="80%">
        <template #default="scope">
          <span class="title-link"  @click="isOpenDialog(scope.row.id  )">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" min-width="80%" width="80%"/>
      <el-table-column label="姓名" prop="name" min-width="80%" width="80%"/>
      <el-table-column label="手机号" prop="phone" min-width="90%" />
      <el-table-column label="类型" prop="type" min-width="80%">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.type===1">{{ orderTypeMap[scope.row.type] ?? '未知' }}</el-tag>
          <el-tag type="warning" v-if="scope.row.type===0">{{ orderTypeMap[scope.row.type] ?? '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" min-width="80%" >
        <template #default="scope">
          <el-tag type="success">{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="address" min-width="100%" />
      <!-- <el-table-column label="操作" min-width="100%">
        <template #default="scope">
          <div class="btn">
            <el-button @click="openDialog(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteWorkorder(scope.row)">删除</el-button>
            <el-button type="primary"  v-if="scope.row.status === 0">分配</el-button>
          </div>
        </template>
      </el-table-column> -->
    </el-table>
    </div>
    <div class="pagination-container" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-sizes="pageSize"
        page-size=10
        :page-sizes="[4, 5, 10, 15]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditDialogOpen" title="编辑工单" >
      <el-form :model="currentWorkorder" label-width="150px" style="width: 600px">
        <el-form-item label="工单ID"  >
          <el-input v-model="currentWorkorder.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="工单标题"  >
          <el-input v-model="currentWorkorder.title"></el-input>
        </el-form-item>
        <el-form-item label="工单描述">
          <el-input v-model="currentWorkorder.des" type="text"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="currentWorkorder.name" type="text"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="currentWorkorder.phone" type="text"></el-input>
        </el-form-item>
         <el-form-item label="地址">
      <!-- 导入地图选点组件 -->
          <MapSelector v-model="addressInfo.address">
        <!-- 通过插槽传入地址输入框 -->
            <template #address-input>
              <el-input v-model="currentWorkorder.address" placeholder="请输入地址或通过地图选择"/>
            </template>
          </MapSelector>
    </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentWorkorder.status">
            <el-option label="待处理" :value="0"/>
            <el-option label="处理中" :value="1"/>
            <el-option label="已处理" :value="2"/>
            <el-option label="已结算" :value="3"/>
            <el-option label="待审核" :value="4"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveWorkorder">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog  v-model="dialogVisible"  title="工单详情" width="50%"  :before-close="handleClose"  custom-class="workorder-detail-dialog" >
      <el-form :model="detailData" label-width="120px" class="detail-form">
        <el-form-item label="ID">{{ detailData.id }}</el-form-item>
        <el-form-item label="标题">{{ detailData.title }}</el-form-item>
        <el-form-item label="描述">{{ detailData.des }}</el-form-item>
        <el-form-item label="姓名">{{ detailData.name }}</el-form-item>
        <el-form-item label="手机号">{{ detailData.phone }}</el-form-item>
        <el-form-item label="地址">{{ detailData.address }}</el-form-item>
        <el-form-item label="状态">
          <el-tag size="small"   :type="detailData.status === 3 ? 'success' : detailData.status === 2 ? 'warning' : detailData.status === 1 ? 'info' : 'default'"   >
            {{ detailData.statusDesc }}
          </el-tag>
        </el-form-item>
        <el-form-item label="星级">
          <el-rate v-model="feedback.rating" text-color="#ff9900" score-template="{value}" disabled />
        </el-form-item>
        <el-form-item label="评价">{{ feedback.comment || '暂无评价' }}</el-form-item>
        <el-form-item label="创建时间">{{ detailData.createTime }}</el-form-item>
        <el-form-item label="更改时间">{{ detailData.updateTime }}</el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible=false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.container {
  padding: 20px;
  background-color: white;
  min-height: 100vh; /* 使用100vh确保占满视口高度，100%可能因父元素高度问题无效 */
  width: 100%;
  display: flex; /* 开启Flex布局 */
  flex-direction: column; /* 子元素垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: flex-start; /* 垂直从顶部开始排列，可根据需要调整 */
}
.workorder-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 15px;
  padding-right: 15px; /* 右侧留与左侧相同的间距 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
  margin-bottom: 15px; /* 与下方表格保持距离 */
}
.search-box {
  padding-left: 15px;
  display: flex; /* 使用Flex布局使输入框和按钮横向排列 */
  align-items: center; /* 垂直居中对齐 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
}
.btn{
  display: flex;
  gap: 2px;
}
/* 表格容器 */
.table_container {
  background-color: white;
  height: 300px;
  width: calc(100% - 30px); /* 宽度与搜索框一致 */
  margin-left: 40px;
  margin-top: 20px;
  box-sizing: border-box; /* 避免边框/内边距影响宽度 */
  align-items: center;
}
.title-link {
  color: #409eff; /* 蓝色，模拟链接样式 */
  cursor: pointer;
  text-decoration: underline; /* 下划线，增强可点击提示 */
}
.addBtn{
  margin-right: 160px;
}
.pagination-container {
  padding: 10px 0;
  align-items: center;
}

</style>
